from typing import Optional, Dict, Any
from sqlalchemy.ext.asyncio import AsyncSession
from fastapi import HTTPException, status
from core.pagination import paging_data, _CustomPageParams

from modules.system.models.staff import Salesperson
from modules.system.schemas.staff_schemas import StaffCreate, StaffUpdate
from modules.system.params.staff_params import StaffQuery
from modules.system.curd.staff_curd import staff_dao
from utils.query_builder import build_select_stmt


class StaffService:
    @staticmethod
    async def get_staff_by_id(db: AsyncSession, staff_id: int) -> Optional[Salesperson]:
        return await staff_dao.get_by_id(db, staff_id)

    @staticmethod
    async def get_staff_with_pagination(db: AsyncSession, query_params: StaffQuery) -> Dict[str, Any]:
        stmt = build_select_stmt(
            Salesperson,
            query_params,
            order_by_desc="id",
            text_like_fields=None
        )
        params = _CustomPageParams(page=query_params.page, size=query_params.size)
        return await paging_data(db, stmt, params=params)

    @staticmethod
    async def create_staff(db: AsyncSession, payload: StaffCreate) -> Salesperson:
        obj = await staff_dao.create(db, payload)
        if not obj:
            raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="业务员创建失败")
        await db.commit()
        await db.refresh(obj)
        return obj

    @staticmethod
    async def update_staff(db: AsyncSession, staff_id: int, payload: StaffUpdate) -> Salesperson:
        obj = await staff_dao.update(db, staff_id, payload)
        if not obj:
            raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="业务员不存在")
        await db.commit()
        await db.refresh(obj)
        return obj

    @staticmethod
    async def delete_staff(db: AsyncSession, staff_id: int) -> None:
        ok = await staff_dao.delete(db, staff_id)
        if not ok:
            raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="业务员不存在")
        await db.commit()
        return True